# Face Detection Example
#
# This example shows off the built-in face detection feature of the OpenMV Cam.
#
# Face detection works by using the Haar Cascade feature detector on an image. A
# Haar Cascade is a series of simple area contrasts checks. For the built-in
# frontalface detector there are 25 stages of checks with each stage having
# hundreds of checks a piece. Haar Cascades run fast because later stages are
# only evaluated if previous stages pass. Additionally, your OpenMV Cam uses
# a data structure called the integral image to quickly execute each area
# contrast check in constant time (the reason for feature detection being
# grayscale only is because of the space requirement for the integral image).
from pyb import millis
import sensor
import time
from time import sleep
import image
import lcd
from pyb import LED,Pin
from os import listdir

library_province = listdir('/library_province')#读取省份模板文件名
library_province.sort()#排序
province_template = []  #省份模板图片
province_similarity = []    #每次识别后所有模板的相似度########
for n in range(len(library_province)):
    province_template.append(image.Image('/library_province/'+library_province[n]))#存入省份模板图
    province_template[n].invert()
    province_similarity.append(0)    #每次识别后所有模板的相似度

library_alphanumeric = listdir('/library_alphanumeric')#读取数字字母模板文件名
library_alphanumeric.sort()#排序
alphanumeric_template = []  #数字字母模板图片
alphanumeric_similarity = []    #每次识别后所有模板的相似度

for n in range(len(library_alphanumeric)):
    alphanumeric_template.append(image.Image('/library_alphanumeric/'+library_alphanumeric[n]))#存入数字字母模板图
    alphanumeric_template[n].invert()
    alphanumeric_similarity.append(0)    #每次识别后所有模板的相似度

license_number = []#存储识别到的结果
for n in range(7):
    license_number.append(' ')#省位的h



# Reset sensor
sensor.reset()

# Sensor settings
sensor.set_contrast(3)
sensor.set_gainceiling(16)
# HQVGA and GRAYSCALE are the best for face tracking.
sensor.set_framesize(sensor.QVGA)
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_contrast(2)
# Load Haar Cascade
# By default this will use all stages, lower satges is faster but less accurate.
face_cascade = image.HaarCascade("cascade.cascade", stages=25)
print(face_cascade)
sensor.skip_frames(time = 5)
blue_led = LED(1)
KEY = Pin('C13',Pin.IN,Pin.PULL_DOWN)
lcd.init(type=2,refresh=120)

# FPS clock
clock = time.clock()

keycount=0

img_GRAYSCALE = sensor.alloc_extra_fb(320,90,sensor.GRAYSCALE)
img_GRAYSCALE_2 = sensor.alloc_extra_fb(320,90,sensor.GRAYSCALE)
img_targets = []
img_targets.append(sensor.alloc_extra_fb(35,55,sensor.GRAYSCALE))
for n in range(6):
    img_targets.append(sensor.alloc_extra_fb(28,45,sensor.GRAYSCALE))

while True:
    clock.tick()

    if KEY.value() == 1:
        sensor.ioctl(sensor.IOCTL_TRIGGER_AUTO_FOCUS)#自动对焦
        blue_led.on()
        sleep(0.05)
    # Capture snapshot
    img = sensor.snapshot()

    img_GRAYSCALE.draw_image(img,0,0) #原图绘制到灰度画布上，用于定位字符
    img_GRAYSCALE_2.draw_image(img_GRAYSCALE,0,0) #复制第二份灰度图，用于识别

    img_GRAYSCALE.laplacian(1)  #通过拉普拉斯变换，突出色彩分界线（数值越大效果越好，但越慢。所以用最小值，再提高画面亮度）
    img_GRAYSCALE.gamma_corr(gamma=1.2,contrast=25) #提高画面伽马值、对比度、亮度
    blobs = img_GRAYSCALE.find_blobs([(2,255)], x_stride=4,y_stride=2,pixels_threshold=80, area_threshold=80, margin=10)

#    for r in blobs:
#        img_GRAYSCALE.draw_rectangle(r)   #img.draw_image(img_targets[n], n*40, 0,)   #将剪切结果绘制到主画布上，以观察效果
    lcd.display(img_GRAYSCALE)
    # Find objects.
    # Note: Lower scale factor scales-down the image more and detects smaller objects.
    # Higher threshold results in a higher detection rate, with more false positives.
    objects = img.find_features(face_cascade, threshold=0.75, scale_factor=1.25)
    timer = millis()#用于计这段消耗的时间，如果耗时过长，需要优化或移植到底层（C语言）
    #1.遍历筛选所有识别结果,筛选条件：自己和其他4个以上元素 高度 和 y坐标 相互相似的目标
    target_blobs=[]
    for n1 in range(len(blobs)):
        find_out_times = 0
        for n2 in range(len(blobs)):
            #判断高度差、Y轴差异度
            if abs(blobs[n1].h() - blobs[n2].h()) < (blobs[n1].h() * 0.2) and \
            abs(blobs[n1].cy() - blobs[n2].cy()) < (blobs[n1].h() * 0.3):
                find_out_times += 1
                if find_out_times > 4:#超过5次符合，记录
                    target_blobs.append(blobs[n1])
                    break
        #2.结果按y轴排序
        target_blobs.sort(key = lambda b: b.y())#按选择框cy排序
    # Draw objects


    for r in objects:
        img.draw_rectangle(r)
        print(r)

    # Print FPS.
    # Note: Actual FPS is higher, streaming the FB makes it slower.
    print(clock.fps())

